package com.h2cloud.threadPool;

import java.util.concurrent.*;

/**
 * @Package: com.h2cloud.threadPool
 * @ClassName: ThreadPoolTest
 * @Author: h2cloud
 * @CreateTime: 2022/9/29 12:00 上午
 * @Description:
 */
public class ThreadPoolTest {

	public static void main(String[] args) {
		final ThreadPoolTest threadPoolTest = new ThreadPoolTest();
		for (int i = 0; i < 1; i++) {
			new Thread(() -> {
				while (true) {
					Future<String> future = threadPoolTest.submit();
					if (future == null){
						System.out.println(future);

					}
					try {
						String s = future.get();
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					} catch (Error e) {
						e.printStackTrace();
					}
				}
			}).start();
		}

		//子线程不停gc，模拟偶发的gc
		new Thread(() -> {
			while (true) {
				System.gc();
			}
		}).start();
	}

	/**
	 * 异步执行任务
	 *
	 * @return
	 */
	public Future<String> submit() {
		//关键点，通过 Executors.newSingleThreadExecutor创建一个单线程的线程池
		ExecutorService executorService = Executors.newSingleThreadExecutor();
		FutureTask<String> futureTask = new FutureTask(new Callable() {
			@Override
			public Object call() throws Exception {
				Thread.sleep(50);
				return System.currentTimeMillis() + "";
			}
		});
		executorService.execute(futureTask);
		return futureTask;
	}

}
